<template>
  <a-modal title-align="start" :title="props.type == 'add' ? '新增标签' : '编辑标签'" :mask-closable="false" v-model:visible="showvisible" @cancel="showvisible = false" :width="600">
    <a-form auto-label-width ref="formRef" size="medium" :model="form">
      <a-form-item field="name" label="名称" :rules="rules.name">
        <a-input v-model="form.name" placeholder="请输入名称" allow-clear />
      </a-form-item>
      <a-form-item field="slug" label="别名" :rules="rules.slug">
        <div style="width: 100%">
          <div> <a-input v-model="form.slug" placeholder="请输入别名" allow-clear /></div>
          <div class="common-text">建议小写字母，并且只包含字母、数字和连字符。</div>
        </div>
      </a-form-item>

      <a-form-item label="描述">
        <a-textarea v-model="form.description" placeholder="请输入" allow-clear />
      </a-form-item>
    </a-form>

    <template #footer class="modal-footer">
      <a-button @click="showvisible = false">取消</a-button>
      <a-button type="primary" :loading="loading" @click="submit">确定</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import { defineComponent, ref, computed, onMounted } from 'vue'
  import { batchTag } from '@/api/product'
  import { Message } from '@arco-design/web-vue'
  let props = defineProps(['modelValue', 'type', 'info', 'shopId'])
  let emits = defineEmits(['save', 'update:modelValue'])
  const formRef = ref()
  let showvisible = computed({
    get() {
      return props.modelValue
    },
    set(val) {
      emits('update:modelValue', val)
    },
  })
  let form = ref({
    name: '',
    slug: '',
    description: '',
  })
  let loading = ref(false)
  let rules = ref({
    name: [{ required: true, message: '请输入名字' }],
    slug: [{ required: true, message: '请输入别名' }],
    parentName: [{ required: true, message: '请选择父级分类' }],
  })

  const submit = async () => {
    const valid = await formRef.value.validate()
    if (valid) return
    let params: any = {
      param: {},
      shopId: props.shopId,
    }
    if (props.type == 'add') {
      let obj = {
        ...form.value,
      }
      params.param.create = [obj]
    } else {
      let obj = {
        ...form.value,
      }
      params.param.update = [obj]
    }

    try {
      loading.value = true
      const res: any = await batchTag(params)
      if (res) {
        Message.success(props.type == 'add' ? '新增成功。当前操作不是立即生效，请等待几分钟后刷新页面' : '编辑成功。当前操作不是立即生效，请等待几分钟后刷新页面')
        emits('save')
        showvisible.value = false
      }
    } catch (error) {}
    loading.value = false
  }

  const init = () => {
    let obj = {
      id: props.info.dataFromRestApi.id,
      name: props.info.dataFromRestApi.name,
      slug: props.info.dataFromRestApi.slug,
      description: props.info.dataFromRestApi.description,
    }
    form.value = obj
  }

  onMounted(() => {
    if (props.type == 'edit') init()
  })
</script>

<style lang="less" scoped></style>
